package com.wephone.Student;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatDB;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMMessage;
import com.easemob.chat.OnMessageNotifyListener;
import com.easemob.chat.OnNotificationClickListener;
import com.easemob.exceptions.EaseMobException;
import com.wephone.Student.huanxin.db.DbOpenHelper;
import com.wephone.Student.huanxin.db.UserDao;
import com.wephone.Student.huanxin.domain.User;
import com.wephone.Student.ui.MainTabBar;

public class BaseApplication extends Application {
	public static Context applicationContext;
	private static BaseApplication instance;
	// login user name
	public final String PREF_USERNAME = "username";
	private String userName = null;
	// login password
	private static final String PREF_PWD = "pwd";
	private String password = null;
	private Map<String, User> contactList;
	protected Vibrator vibrator;

	@Override
	public void onCreate() {
		super.onCreate();
		
		applicationContext = this;
		instance = this;
		
		initEmChat();
	}
	
	public void initEmChat(){
		int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        
        // 如果app启用了远程的service，此application:onCreate会被调用2次
        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        // 默认的app会在以包名为默认的process name下运行，如果查到的process name不是app的process name就立即返回
        if (processAppName == null ||!processAppName.equalsIgnoreCase("com.wephone.Student")) {
            //"com.easemob.chatuidemo"为demo的包名，换到自己项目中要改成自己包名
            
            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
     // 初始化环信聊天SDK
     		Log.d("EMChat Demo", "initialize EMChat SDK");
     		EMChat.getInstance().setDebugMode(false);
     		EMChat.getInstance().init(applicationContext);
     		EMChat.getInstance().setAutoLogin(false);
     		//EMChatManager.getInstance().logout();
     		// 获取到EMChatOptions对象
     		EMChatOptions options = EMChatManager.getInstance().getChatOptions();
     		// 设置收到消息是否有新消息通知，默认为true
     		options.setNotificationEnable(true);
     		// 设置收到消息是否有声音提示，默认为true
     		options.setNoticeBySound(false);
     		// 设置收到消息是否震动 默认为true
     		options.setNoticedByVibrate(false);
     		// 设置语音消息播放是否设置为扬声器播放 默认为true
     		options.setUseSpeaker(true);
     		 vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
     		//设置notification消息点击时，跳转的intent为自定义的intent
     		options.setOnNotificationClickListener(new OnNotificationClickListener() {
     			@Override
     			public Intent onNotificationClick(EMMessage message) {
     				Intent intent = new Intent(applicationContext, MainTabBar.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
     		                Intent.FLAG_ACTIVITY_CLEAR_TASK |
     		                Intent.FLAG_ACTIVITY_NEW_TASK);
     				intent.putExtra("showChatHistoryPage", true);
     				return intent;
     			}
     		});
     		//取消注释，app在后台，有新消息来时，标题栏的消息提示换成自己写的
     		options.setNotifyText(new OnMessageNotifyListener() {
     			@Override
     			public String onNewMessageNotify(EMMessage message) {
//     				try {
//     					String chatUser = message.getStringAttribute("chatUserName");
//     					if(!TextUtils.isEmpty(chatUser)){
//     						return "你的好友" + chatUser + "发来了一条消息";
//     					}
//     				} catch (EaseMobException e) {
//     					e.printStackTrace();
//     				}
     				long[] pattern = new long[] { 0, 300, 150, 200 };
     	            vibrator.vibrate(pattern, -1);
     				return "山楂僧发来了1条消息";
     			}
     			
     			@Override
     			public String onLatestMessageNotify(EMMessage message, int fromUsersNum, int messageNum) {
//     				return fromUsersNum + "个好友发来" + messageNum + "条消息";
     				long[] pattern = new long[] { 0, 300, 150, 200 };
     	                vibrator.vibrate(pattern, -1);
     				return "山楂僧发来了" + messageNum + "条消息";
     			}

     			@Override
     			public String onSetNotificationTitle(EMMessage arg0) {
     				// TODO Auto-generated method stub
     				return null;
     			}

     			@Override
     			public int onSetSmallIcon(EMMessage arg0) {
     				// TODO Auto-generated method stub
     				return 0;
     			}
     		});
        
	}
	 /**
     * check the application process name if process name is not qualified, then we think it is a service process and we will not init SDK
     * @param pID
     * @return
     */
    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
                    // info.processName +"  Label: "+c.toString());
                    // processName = c.toString();
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }
    

	
	public static BaseApplication getInstance() {
		return instance;
	}

	
	/**
	 * 获取内存中好友user list
	 * 
	 * @return
	 */
	public Map<String, User> getContactList() {
		if(getUserName() != null &&contactList == null)
		{
			UserDao dao = new UserDao(applicationContext);
			// 获取本地好友user list到内存,方便以后获取好友list
			contactList = dao.getContactList();
		}
		return contactList;
	}

	/**
	 * 设置好友user list到内存中
	 * 
	 * @param contactList
	 */
	public void setContactList(Map<String, User> contactList) {
		this.contactList = contactList;
	}

	/**
	 * 获取当前登陆用户名
	 * 
	 * @return
	 */
	public String getUserName() {
		if (userName == null) {
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
			userName = preferences.getString(PREF_USERNAME, null);
		}
		return userName;
	}

	/**
	 * 获取密码
	 * 
	 * @return
	 */
	public String getPassword() {
		if (password == null) {
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
			password = preferences.getString(PREF_PWD, null);
		}
		return password;
	}

	/**
	 * 设置用户名
	 * 
	 * @param user
	 */
	public void setUserName(String username) {
		if (username != null) {
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
			SharedPreferences.Editor editor = preferences.edit();
			if (editor.putString(PREF_USERNAME, username).commit()) {
				userName = username;
			}
		}
	}

	/**
	 * 设置密码
	 * 
	 * @param pwd
	 */
	public void setPassword(String pwd) {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
		SharedPreferences.Editor editor = preferences.edit();
		if (editor.putString(PREF_PWD, pwd).commit()) {
			password = pwd;
		}
	}

	/**
	 * 退出登录,清空数据
	 */
	public void logout() {
		// 先调用sdk logout，在清理app中自己的数据
		EMChatManager.getInstance().logout();
		DbOpenHelper.getInstance(applicationContext).closeDB();
		EMChatDB.getInstance().deleteConversions(getUserName());
		// reset password to null
		setPassword(null);
//		setContactList(null);

	}

//	private String getAppName(int pID) {
//		String processName = null;
//		ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
//		List l = am.getRunningAppProcesses();
//		Iterator i = l.iterator();
//		PackageManager pm = this.getPackageManager();
//		while (i.hasNext()) {
//			ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
//			try {
//				if (info.pid == pID) {
//					CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
//					// Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
//					// info.processName +"  Label: "+c.toString());
//					// processName = c.toString();
//					processName = info.processName;
//					return processName;
//				}
//			} catch (Exception e) {
//				// Log.d("Process", "Error>> :"+ e.toString());
//			}
//		}
//		return processName;
//	}
	
}
